var crypto = require('crypto');
var querystring = require('querystring');
var randomString = require('random-string');

/**
 * md5加密
 * @param str
 * @returns {*}
 */
exports.md5 = function(str){
    var md5 = crypto.createHash('md5');
    md5.update(str);
    return md5.digest('hex').toUpperCase();
}
/**
 * sha1加密
 * @param str
 * @returns {string}
 */
exports.sha1 = function(str){
    var sha1 = crypto.createHash('sha1');
    sha1.update(str);
    return sha1.digest('hex').toUpperCase();
}
/**
 * 字典排序
 * @param obj
 * @returns {{}}
 */
exports.ksort = function(obj){
    var arr = [];
    for(key in obj){
        arr.push(key);
    }
    var sorted = arr.sort();
    var tempObj = {};
    for(key in sorted){
        tempObj[sorted[key]] = obj[sorted[key]];
    }
    return tempObj;
}
/**
 * 连接属性字符串
 * @param obj
 * @returns {string}
 */
exports.concat = function(obj){
    var str = ''
    for(key in obj){
        str += (key + '=' + obj[key])
    }
    return str;
}

/**
 * 生成随即字符串
 * @param len
 * @returns {*}
 */
exports.generateNonce = function(len){
    return randomString({length: len})
}
/**
 * 生成时间戳
 * @returns {number}
 */
exports.generateTimeStamp = function(){
    return Math.round(new Date().getTime()/1000)+'';
}

exports.stringify = function(obj){
    return querystring.stringify(obj);
}
